package com.lzp.systemopt.messenger

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log

/**
 * @description:
 * @author: lxp
 * @date: 2022/3/17 下午4:36
 */
class MessengerManager {

    companion object {
        private const val TAG = "MessengerManager"
        val instance by lazy { MessengerManager() }
    }

    private var mService: Messenger? = null
    private var isConn = false

    fun bindService(activity: Activity) {
        val intent = Intent()
        //todo 这里要约定好
        intent.action = "com.lzp.aidl.messenger"
        intent.setPackage("com.lzp.appexp")
        activity.bindService(intent, mConn, Context.BIND_AUTO_CREATE)
    }

    fun unbindService(activity: Activity) {
        activity.unbindService(mConn)
    }

    private val mMessenger = Messenger(object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                MessengerService.MSG_ID -> {
                    val data = msg.data
                    val string = data.getString("data")
                    val len = string?.length?:0
                    Log.d(TAG, "客户端 》》》 收到消息：${string?.substring(len-10,len)}")
                }
            }
        }
    })

    private var mConn:ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mService = Messenger(service)
            isConn = true
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            mService = null
            isConn = false
        }
    }

    fun sendMessage(msg: String) {
        val message = Message.obtain(null, MessengerService.MSG_ID)
        val bundle = Bundle()
        bundle.putString("data",msg)
        message.data = bundle
        message.replyTo = mMessenger
        if (isConn) {
            mService?.send(message)
        }
    }
}